package com.chenpp.netty.tomcat.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

import java.io.UnsupportedEncodingException;

/**
 * 2020/3/9
 * created by chenpp
 */
public class CPResponse {

    private ChannelHandlerContext context ;

    public CPResponse(ChannelHandlerContext context){
        this.context = context;
    }

    public void write(String content)  {
        //设置Http请求头
        //设置http版本为1.1,响应状态码为200，设置输出的编码
        FullHttpResponse response = null;
        try {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(content.getBytes("UTF-8")));
            response.headers().set("Content-Type", "text/html;");
            context.write(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }finally {
            if(content != null){
                context.flush();
                context.close();
            }
        }
    }


}
